/**
 * @Description: 路由 - 守卫
 * @Author: Zander
 * @Date: 2023/2/2 16:55
 * @LastEditors: Zander
 * @LastEditTime: 2023/2/2 16:55
 */
import { getToken } from '@utils/auth';
import store from '@/store';
// 路由跳转类型
const ROUTER_TYPE = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab'];

// 路由白名单，不需要登录页面
const WHITE_LIST = ['/pages/login/login']

class Permission {
  constructor() {
    // 进入页面初始化Vuex信息
    store.dispatch('user/getUserInfo').then();
  }

  intercept(options) {
    const { query } = options;

    // 添加拦截器
    ROUTER_TYPE.forEach(routerType => {
      uni.addInterceptor(routerType, {
        invoke(args) {
          const url = args.url.split('?')[0];
          let pass = true;
          if (!getToken()) {
            pass = WHITE_LIST.some(item => {
              if (typeof item === 'object' && item?.pattern) item.pattern.test(url)
              return item === url;
            })
          }
          if (!pass) {
            const type = url.indexOf('tabBar') > -1 ? 'switchTab' : 'redirectTo'
            uni.setStorageSync('REDIRECT', { url, type, query });
            uni.reLaunch({
              url: '/pages/login/login'
            })
            return false
          }
          return args;
        }
      })
    })
  }
}

export const permission = new Permission();
